#product
#handles all Owner related stuff
import os
from google.appengine.ext import db
from google.appengine.api import mail
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import sys

class NotFound(Exception): pass

class Owner(db.Model):
	firstName = db.StringProperty(multiline=False)
	lastName = db.StringProperty(multiline=False)
	birthDate = db.DateTimeProperty(auto_now_add=True)
	user = db.StringProperty(multiline=False)
	
	#Throws NotFound
	def find(email): 
		query = Owner.all()
	
		query.filter('user =', email)
		try:
			result = query.fetch(1)
			owner=result[0]
		except IndexError:
			raise NotFound()
		
		return owner
	#make find static	
	find=staticmethod(find)
	
class Register(webapp.RequestHandler):
	def get(self):
		loggedInuser = users.get_current_user()
	
		if loggedInuser:
			try:
				owner = Owner.find(loggedInuser.email())
			except NotFound:
				owner = Owner()

			template_values = {
			      'owner': owner
				}	
			path = os.path.join(os.path.dirname(__file__), 'register.html')
			self.response.out.write(template.render(path, template_values))
		else:
			self.redirect('/')
	
	def post(self):
		loggedInuser = users.get_current_user()
		
		if loggedInuser:
			try:
				owner = Owner.find(loggedInuser.email())
			except NotFound:
				owner = Owner()
	
		owner.firstName = self.request.get("firstname")
		owner.lastName = self.request.get("lastname")
		sys.stderr.write('voornaam =' + owner.firstName)
		sys.stderr.write('achternaam =' + owner.lastName)
		#if self.request.get("birthdate"):
		#	owner.birthDate = self.request.get("birthdate")
		owner.user = users.get_current_user().email()
		owner.put()
		user_address = self.request.get("email")

		
		confirmation_url = users.CreateLoginURL(self.request.uri)
		sender_address = "bittebak@gmail.com"
		subject = "Confirm your registration"
		body = """
		Thank you for creating an account!  Please confirm your email address by
		clicking on the link below:

		%s
		""" % confirmation_url

		mail.send_mail(sender_address, users.get_current_user().email(), subject, body)
		self.redirect('/wish/mylist')
		
		
application = webapp.WSGIApplication(
                                     [('/owner/register', Register)],
                                      debug=True)
                                      

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()	                                      